﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Data.Common;
using System.Data.Linq;
using System.Data.Objects;

namespace Mall.Infrastructure.EnityFramework
{
	/// <summary>
	/// 扩展
	/// </summary>
	public static class TableExtensions
	{
		/// <summary>
		/// 批量删除
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="table">表</param>
		/// <param name="predicate">查询条件表达式</param>
		/// <returns>影响的行数</returns>
        public static int Delete<T>(this ObjectSet<T> table, Expression<Func<T, bool>> predicate) where T : class
		{

            //获取表名
            string tableName = string.Format("[{0}]", table.EntitySet.Name);

			//查询条件表达式转换成SQL的条件语句
			ConditionBuilder builder = new ConditionBuilder();
			builder.Build(predicate.Body);
			string sqlCondition = builder.Condition;

			//SQL命令
			string commandText = string.Format("DELETE FROM {0} WHERE {1}", tableName, sqlCondition);

			//获取SQL参数数组 
			var args = builder.Arguments;

			//执行
            return table.Context.ExecuteStoreCommand(commandText, args);
		}


		/// <summary>
		/// 批量更新
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="table">表</param>
		/// <param name="predicate">查询条件表达式</param>
		/// <param name="updater">更新表达式</param>
		/// <returns>影响的行数</returns>
        public static int Update<T>(this ObjectSet<T> table, Expression<Func<T, T>> updater, Expression<Func<T, bool>> where) where T : class
		{
			//获取表名
            string tableName =string.Format("[{0}]",table.EntitySet.Name);

			//查询条件表达式转换成SQL的条件语句
			ConditionBuilder builder = new ConditionBuilder();
			builder.Build(where.Body);

            //获取更新实例
            PartialEvaluator evaluator = new PartialEvaluator();
            ConstantExpression evaluatedExpression = evaluator.Eval(updater.Body) as ConstantExpression;
            var item = evaluatedExpression.Value;


			string sqlCondition = builder.Condition;

			//获取Update的赋值语句
			var updateMemberExpr = (MemberInitExpression)updater.Body;
			var updateMemberCollection = updateMemberExpr.Bindings.Cast<MemberAssignment>().Select(c => new
			{
				Name = c.Member.Name,
                Value = (c.Expression as ConstantExpression) == null ?   item.GetType().GetProperty(c.Member.Name).GetValue(item, null) : ((ConstantExpression)c.Expression).Value
			});

			int i = builder.Arguments.Length;

            string sqlUpdateBlock = ""; //值
            string commandText = ""; //SQL语句
            object[] args = null; //SQL 参数

			//SQL命令(针对m=>true)
            if (builder.Arguments.Count() == 1 && builder.Arguments[0] is bool && ((bool)builder.Arguments[0]) && sqlCondition == "{0}")
            {
                i = 0;
                sqlUpdateBlock = string.Join(", ", updateMemberCollection.Select(c => string.Format("[{0}]={1}", c.Name, "{" + (i++) + "}")).ToArray());
                commandText = string.Format("UPDATE {0} SET {1} ", tableName, sqlUpdateBlock);
                args = updateMemberCollection.Select(c => c.Value).ToArray();
            }
            else
            {
                sqlUpdateBlock = string.Join(", ", updateMemberCollection.Select(c => string.Format("[{0}]={1}", c.Name, "{" + (i++) + "}")).ToArray());

                commandText = string.Format("UPDATE {0} SET {1} WHERE {2}", tableName, sqlUpdateBlock, sqlCondition);
                //获取SQL参数数组 (包括查询参数和赋值参数)
                args = builder.Arguments.Concat(updateMemberCollection.Select(c => c.Value)).ToArray();
            }


            //执行
            return table.Context.ExecuteStoreCommand(commandText, args);
		}

        public static void Update<T>(T entity)
        { 
            
        }

	}
}
